import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'

import Guide from '@/views/Guide/Guide.vue'
import { routerTypes } from '../utils/types'
import { ErrorRoutes } from '../views/ErrorPage/route'
import { LoginRoutes } from '../views/Logins/route'
import { MainRoutes } from '../views/Main/route'
import { useStore } from './../store/index';
import { routerList } from '../utils/routerList'
import { Http } from '../api/api'

const routes: Array<routerTypes> = [
    {
        path: "/",
        redirect: "/login",
    },
    ...LoginRoutes,
    {
        path: '/guide/:uname?',
        name: 'guide',
        component: Guide,
    },
    ...ErrorRoutes,
    ...MainRoutes,

]


const router = createRouter({
    history: createWebHashHistory(),
    routes,

})


const getRouterListByRole = (arr: any, role: Number) => {
    let newList: any = arr.filter((item: any) => {
        if (item.max) {
            return role >= item.role && role <= item.max;
        } else {
            return role >= item.role
        }
    })
    newList.forEach((item: any) => {
        if (item.children) {
            return (item.children = getRouterListByRole(item.children, role)) // 第二层循环 
        }
    })
    return newList
}


router.beforeEach(async (to, from, next) => {
    const store = useStore()
    const { changeurlList, myRouterList, getMyRouterList, changefromRouteName } = store;
    if (to.name) {
        changeurlList(to)
    }

    changefromRouteName(from.name);
    const name = to.name;
    if (name == 'login' || name == 'findpass' || name == 'register' || name == '404' || name == '503' || name == 'guide') {
        next()
    } else {
        if (myRouterList && myRouterList.length > 0) {
            next()
        } else {
            getMyRouterList([])
            let res = await Http.getuserinfo() as any;
            let list = getRouterListByRole(routerList, res.result.role)
            getMyRouterList([...list])

            router.addRoute({
                name: 'main',
                path: '/main',
                component: () => import("@/views/Main/Main.vue"),
                children: list
            })
            router.addRoute({
                path: "/:pathMatch(.*)*",
                redirect: "/404"
            })

            next({ ...to, replace: true })
        }
    }
})
export default router